package com.zhao.dota.common;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.zhao.dota.common.contant.BaseEnum;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class EnumWebSerializer extends JsonSerializer<BaseEnum> {

    private List<String> ignoreMethodNames = new ArrayList<String>() {{
        add("getDesc");
        add("getClass");
        add("getDeclaringClass");
    }};

    @Override
    public void serialize(BaseEnum value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
        if (value == null) {
            gen.writeNull();
            return;
        }
        Map<String, Object> map = new HashMap<>();
        map.put("desc", value.getDesc());
        map.put("name", value.name());
        map.put("ordinal", value.ordinal());
        Method[] methods = value.getClass().getMethods();
        for (Method method : methods) {
            String name = method.getName();
            if (!name.startsWith("get") || ignoreMethodNames.contains(name)) {
                continue;
            }
            if (method.getParameterCount() > 0) {
                continue;
            }

            name = name.substring(3);
            try {
                map.put(name.substring(0, 1).toLowerCase() + name.substring(1), method.invoke(value));
            } catch (IllegalAccessException | InvocationTargetException ignore) {
            }
        }
        gen.writeObject(map);
    }

    @Override
    public Class<BaseEnum> handledType() {
        return BaseEnum.class;
    }

}
